package com.niji.littly_donkey_android.activity;


import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaTimestamp;
import android.net.Uri;
import android.os.Bundle;
import android.os.FileUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.adapter.LoadPicAdatper;
import com.niji.littly_donkey_android.bean.LoadFile;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.BitMapUtil;
import com.niji.littly_donkey_android.util.GlideEngine;
import com.niji.littly_donkey_android.adapter.MainAdapter;
import com.niji.littly_donkey_android.util.UrlUtil;
import com.niji.littly_donkey_android.view.StarRatingView;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class OrderCommentActivity extends BaseActivity {

    /**
     * 选择的图片集
     */
    private ArrayList<Photo> selectedPhotoList = new ArrayList<>();

    /**
     * 返回按钮
     */
    private Button order_comment_return;
    /**
     * 选择图片
     */
    private Button order_comment_select_photo;


    /**
     * 评分星星
     */
    private StarRatingView order_comment_star;

    /***
     * 评分计数
     */
    private int count;

    List<LoadFile> files = new ArrayList<>();

    LoadPicAdatper loadPicAdatper = null;

    private RecyclerView comment_recycler_view;

    private Button order_comment_submit_btn;


    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.comment_activity);
        orderCommentReturn();
//        selectPhoto();
        init();
        initAdapter();
        OrderCommentSubmit();
    }

    /**
     * 提交评论
     */
    private void OrderCommentSubmit() {
        order_comment_submit_btn = findViewById(R.id.order_comment_submit_btn);
        order_comment_submit_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentSubmit();
            }
        });
    }

    /**
     * 提交到服务器
     */
    private void commentSubmit() {
        String url = UrlUtil.URL + "/attractions/add/comment";
        EditText order_comment_content = findViewById(R.id.order_comment_content);
        StarRatingView order_comment_star = findViewById(R.id.order_comment_star);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i <files.size() ; i++) {
            File f = files.get(i).getFile();
            if (f != null) {
                builder.addFormDataPart("img", f.getName(), RequestBody.create(MediaType.parse("image/*"), f));
            }
        }
        Intent intent = getIntent();
        String attractions_id = intent.getStringExtra("attractions_id");
        String content = order_comment_content.getText().toString().trim();
        int score = order_comment_star.getScore();
        builder.addFormDataPart("id",attractions_id);
        builder.addFormDataPart("score",String.valueOf(score));
        builder.addFormDataPart("content",content);
        MultipartBody requestBody = builder.build();
        String sesseionid = new ConnectViaSession(OrderCommentActivity.this).GetSession();
        //构建请求
        Request request = new Request.Builder()
                .url(url)//地址
                .post(requestBody)//添加请求体
                .addHeader("cookie",sesseionid)
                .build();
        final OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                System.out.println("上传照片成功：response = " + response.body().string());
                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                finish();
            }
        });
    }

    /**
     * 初始化adapter
     */
    private void initAdapter() {
        comment_recycler_view = findViewById(R.id.comment_recycler_view);
        files.add(new LoadFile());
        loadPicAdatper = new LoadPicAdatper(OrderCommentActivity.this, files, 3);
        comment_recycler_view.setAdapter(loadPicAdatper);
        comment_recycler_view.setLayoutManager(new GridLayoutManager(this, 3));
        loadPicAdatper.setListener(new LoadPicAdatper.OnItemClickListener() {
            @Override
            public void click(View view, int position) {
                if (files.size() > 3) {
                    Toast.makeText(OrderCommentActivity.this, "一次最多只能传三张照片", Toast.LENGTH_SHORT).show();
                } else {
                    selectPictures();
                }
            }

            @Override
            public void del(View view) {


            }
        });

    }


    String mPhtotPath;
    Uri uriImage;
    File mPhotoFile = null;

    private void selectPictures() {
        //动态申请权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);
        }
        final CharSequence[] items = {"相册"};
        AlertDialog.Builder dlg = new AlertDialog.Builder(OrderCommentActivity.this);
        dlg.setTitle("添加图片");
        dlg.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 0);
                }
            }
        }).create();
        dlg.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1){
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;
            Bitmap bitmap = BitmapFactory.decodeFile(mPhtotPath, options);
            if(bitmap != null){
                if(uriImage != null){
                    saveUritoFile(uriImage,1);
                }
                if(!bitmap.isRecycled()){
                    bitmap.recycle();
                    System.gc();
                }
            }
        }
        if(requestCode == 0){
            if(data != null){
                Uri uri = data.getData();
                saveUritoFile(uri,0);

            }
        }
    }

    private void saveUritoFile(Uri uri, int type) {
        Bitmap photoBmp = null;

        if(uri != null){
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;
                photoBmp = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uri),null,options);
                File file = new File("");
                if(type == 0){
                    file = new File(BitMapUtil.getRealPathFromURI(uri, this));
                }else {
                    if(mPhotoFile != null){
                        file = mPhotoFile;
                    }
                }
                files.add(new LoadFile(file,0,false,photoBmp));
                if(files.size() > 3){
                    files.remove(0);
                }

                loadPicAdatper.notifyDataSetChanged();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.comment_activity;

    }

    @Override
    protected int getStatusBarColor() {
        return R.color.white_easy_photos;
    }

    /**
     * 初始化评分星星
     */
    private void init() {
        order_comment_star = findViewById(R.id.order_comment_star);
        order_comment_star.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count++;
                order_comment_star.setRate(count);
                System.out.println(count);
            }
        });


    }


//    /***
//     * 评论选择照片
//     */
//    private void selectPhoto() {
//        order_comment_select_photo = findViewById(R.id.order_comment_select_photo);
//        show_photo = findViewById(R.id.show_photo);
//        order_comment_select_photo.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//
//                EasyPhotos.createAlbum(OrderCommentActivity.this, true, GlideEngine.getInstance())
//                        .setFileProviderAuthority("com.niji.littly_donkey_android.fileprovider")
//                        .setCount(3)
//                        .start(new SelectCallback() {
//                            @Override
//                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
//                                selectedPhotoList.addAll(photos);
//                                adapter.notifyDataSetChanged();
//
//                            }
//
//
//                        });
//                }
//            });
//
//
//
//    }


    /**
     * 返回按钮
     */
    private void orderCommentReturn() {
        order_comment_return = findViewById(R.id.order_comment_return);
        order_comment_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                finish();
            }
        });

    }
}
